package com.raspbian.monitor.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.raspbian.monitor.bean.ChangePasswordReq;
import com.raspbian.monitor.entity.LoginResp;
import com.raspbian.monitor.entity.SysUser;
import com.raspbian.monitor.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 注册
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/doRegister")
    public R doRegister(@RequestBody SysUser sysUser) {
        return sysUserService.registUser(sysUser);
    }

    /**
     * 登录
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/doLogin")
    public LoginResp doLogin(@RequestBody SysUser sysUser) {
        return sysUserService.login(sysUser);
    }

    @PostMapping("/changePassword")
    @Transactional(rollbackFor = Exception.class)
    public R changePassword(@RequestBody ChangePasswordReq req) {
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", req.getUserName())
                .eq("password", req.getOriginPassword());
        SysUser sysUser = sysUserService.getOne(userQueryWrapper);
        if (sysUser != null) {
            sysUser.setPassword(req.getNewPassword());
            sysUserService.updateById(sysUser);
            return R.ok("修改成功");
        } else {
            return R.failed("原密码输入错误！");
        }
    }

    /**
     * 注销
     *
     * @param response
     * @return
     */
    @GetMapping(value = "/logout")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Void> logout(HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipals() != null) {
            SysUser user = (SysUser) subject.getPrincipals().getPrimaryPrincipal();
            user.setToken("");
            sysUserService.updateById(user);
        }
        SecurityUtils.getSubject().logout();
        response.setHeader("x-auth-token", "");
        return ResponseEntity.ok().build();
    }
}
